
const loginApiUrl = process.env.VUE_APP_BRACELET_API
const current=new Date().getTime()
// console.log(current,'current  登录 /退出登录')

const characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
const charactersLength = characters.length;
for (let i = 0; i < 16; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
}

const requestId=current+result
const braceletRequest = (url, method, params, contentType) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: loginApiUrl + url, // 测试接口
            method: method,
            data: params,
            header: {
                'content-type': contentType || 'application/json',
                'X-Request-Id':'miniprogram-req-'+ requestId
            }
        }).then((response) => {
            // console.log(response,'response登录')
            const res = response
            if (res.statusCode === 500) {
                uni.showToast({
                    icon: 'none',
                    title: res.data.message || '服务暂时不可用，请稍后重试',
                    duration: 2000
                })
                return Promise.reject(res.data.message) // 阻断后续流程
            }else if (res.statusCode === 401 || res.data.code === -1) {
                // 接口出问题，可能是token失效了，返回登陆页
                uni.clearStorage()
                uni.navigateTo({
                    url: '/pages/login/loginSelect'
                })
            }else {
                resolve(res.data)
            }
        })
        .catch(error => {
            console.log(error,'error--login')
            // 弹出消息提示
            // uni.showToast({
            //     icon: 'none', // 不显示图标，最多显示2行
            //     title: '服务器错误！',
            //     duration: 2000
            // })
            // const err = error
            // reject(err)
            const serverMsg = (error?.includes("服务器内部错误") || error?.message?.includes("服务器内部错误") ) ? '服务器内部错误' : (error?.data?.msg || error?.errMsg || error || error?.message || '未知错误')
            const isNetworkError = error?.errMsg?.includes("request:fail") || error?.errMsg?.includes("timeout") || error?.errMsg?.includes("Network Error")
            uni.showToast({
                icon: 'none',
                title: isNetworkError ? '网络连接异常' : (serverMsg || '请求失败'),
                duration: 2000
            })
            return Promise.reject(error) // 阻断后续流程
        })
    })
}

// 退出登录  logout
const  baseLogoutRequest = (url, method, params, contentType) => {
    console.log(uni.getStorageSync('access_token'))
    const token = uni.getStorageSync('access_token')
    const refreshToken=uni.getStorageSync('refreshToken')
    return new Promise((resolve, reject) => {
        uni.request({
            url: loginApiUrl + url, // 测试接口
            method: method,
            data: params,
            header: {
                'Content-Type': contentType || 'application/json',
                'Authorization': 'Bearer ' + token,
                'X-Request-Id':'miniprogram-req-'+ requestId
            }
        }).then((response) => {
            console.log(response, 'response退出登录')
            const res = response
            if (res.statusCode === 500) {
                uni.showToast({
                    icon: 'none',
                    title: res.data.message || '服务暂时不可用，请稍后重试',
                    duration: 2000
                })
                return Promise.reject(res.data.message) // 阻断后续流程
            }else if(res.data.accessTokenExpired==="true" ||res.data.refreshExpiredCode ===true || res.statusCode === 401 || res.data.code === -1){
               console.log(res.data.accessTokenExpired,'accessTokenExpired')
                // 接口出问题，可能是token失效了，返回登陆页
                uni.removeStorageSync('access_token');
                uni.removeStorageSync('userInfo');
                uni.navigateTo({
                    url: '/pages/login/loginSelect'
                })
            }else {
                resolve(res.data)
                // 退出后  返回上一级 首页--我的
                uni.removeStorageSync('access_token');
                uni.removeStorageSync('userInfo');
                uni.switchTab({ url: '/pages/my/mine' })
            }
        }).catch(error => {
            console.log(error,'error')
            // // 弹出消息提示
            // uni.showToast({
            //     icon: 'none', // 不显示图标，最多显示2行
            //     title: '服务器错误！',
            //     duration: 2000
            // })
            // const err = error[0]
            // reject(err)
            const serverMsg = (error?.includes("服务器内部错误") || error?.message?.includes("服务器内部错误") ) ? '服务器内部错误' : (error?.data?.msg || error?.errMsg || error || error?.message || '未知错误')
            const isNetworkError = error?.errMsg?.includes("request:fail") || error?.errMsg?.includes("timeout") || error?.errMsg?.includes("Network Error")
            uni.showToast({
                icon: 'none',
                title: isNetworkError ? '网络连接异常' : (serverMsg || '请求失败'),
                duration: 2000
            })
            return Promise.reject(error) // 阻断后续流程
        })
    })
}

export default {
    braceletRequest,
    baseLogoutRequest
}
